var util = require('../../../utils/util.js');
var api = require('../../../config/api.js');
var app = getApp();
Page({
  data: {
    username: '',
    password: '',
    confirmPassword: '',
    code: '',
    loginErrorCount: 0
  },
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    // 页面渲染完成

  },
  onReady: function () {

  },
  onShow: function () {
    // 页面显示

  },
  onHide: function () {
    // 页面隐藏

  },
  onUnload: function () {
    // 页面关闭

  },
  startRegister: function () {
    var that = this;

    if (that.data.password.length < 3 || that.data.username.length < 3) {
      wx.showModal({
        title: '错误信息',
        content: '用户名和密码不得少于3位',
        showCancel: false
      });
      return false;
    }

    if (that.data.password != that.data.confirmPassword) {
      wx.showModal({
        title: '错误信息',
        content: '确认密码不一致',
        showCancel: false
      });
      return false;
    }

    wx.request({
      url: api.ApiRootUrl + 'auth/register',
      data: {
        username: that.data.username,
        password: that.data.password
      },
      method: 'POST',
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        if (res.data.code == 200) {
          that.setData({
            'loginErrorCount': 0
          });
          wx.setStorage({
            key: "token",
            data: res.data.data.token,
            success: function () {
              wx.switchTab({
                url: '/pages/ucenter/index/index-new'
              });
            }
          });

        }
        console.log(res.data.data.token)
      }
    });
  },
  bindUsernameInput: function (e) {

    this.setData({
      username: e.detail.value
    });
  },
  bindPasswordInput: function (e) {

    this.setData({
      password: e.detail.value
    });
  },
  bindConfirmPasswordInput: function (e) {

    this.setData({
      confirmPassword: e.detail.value
    });
  },
  bindCodeInput: function (e) {

    this.setData({
      code: e.detail.value
    });
  },
  clearInput: function (e) {
    switch (e.currentTarget.id) {
      case 'clear-username':
        this.setData({
          username: ''
        });
        break;
      case 'clear-password':
        this.setData({
          password: ''
        });
        break;
      case 'clear-confirm-password':
        this.setData({
          confirmPassword: ''
        });
        break;
      case 'clear-code':
        this.setData({
          code: ''
        });
        break;
    }
  },
  getPhoneNumber:function (e) {
    wx.showLoading({
      title: '登录中...',
      mask:true
    });
    var that = this;
    var shareId = wx.getStorageSync("shareId");
    var spreadId = wx.getStorageSync("spreadId");
    if (!e.detail.encryptedData || !e.detail.iv){
        return;
    }
    wx.checkSession({
      success:function(){
        //session 未过期
	    	var customerId = wx.getStorageSync("customerId");
        //如果用户id信息还在，直接用用户id获取信息
        if(customerId){
          //请求用户信息
          var data={
            id:wx.getStorageSync("customerId"),
            shareType:wx.getStorageSync("shareType")
          }
          util.request(api.UserDetail, data).then(function (res) {
            if (res.code === '200') {
             wx.setStorageSync("token", res.datas.token);
             wx.setStorageSync("openId",res.datas.openId);
             wx.setStorageSync("type", res.datas.type)
            //  wx.setStorageSync("auth", res.data.auth);
             if("0"==res.datas.type||"1"==res.datas.type){
               //供应商登录
               wx.setStorageSync("shareId", res.datas.customerId);
             }
             wx.showToast({
               title: '登录成功',
               duration: 1000,
               mask: true
             })
             setTimeout(function () {
               wx.navigateBack({});
             }, 1000);
            }else{
              wx.login({
                success: function (result) {
                  var code = result.code;
                  wx.getUserInfo({
                    success: function (res) {
                      //存储为全局变量
                      app.globalData.userInfo = res.userInfo;
                      var data = {
                        iv: res.iv,
                        _iv: e.detail.iv,
                        encryptedData: res.encryptedData,
                        _encryptedData: e.detail.encryptedData,
                        code: code,
                        shareId: shareId,
                        spreadId: spreadId,
                        shareType: wx.getStorageSync("shareType")
                      };
                      util.request(api.UserLogin, data).then(function (res) {
                        if (res.code === '200') {
                          var customerId = res.datas.customerId;
                          var openId = res.datas.openId;
                          var token = res.datas.token;
                          var sessionKey = res.datas.sessionKey;
                          wx.setStorageSync("customerId", customerId);
                          wx.setStorageSync("openId", openId);
                          wx.setStorageSync("token", token);
                          wx.setStorageSync("sessionKey", sessionKey);
                          wx.setStorageSync("type", res.datas.type);
                          // wx.setStorageSync("auth", res.datas.auth);
                          if ("0" == res.datas.type || "1" == res.datas.type) {
                            //供应商登录
                            wx.setStorageSync("shareId", res.datas.customerId);
                          } else {
                            //推广人或者消费者登录
                            if (res.datas.shareId) {
                              wx.setStorageSync("shareId", res.datas.shareId)
                            }
                          }
                          wx.showToast({
                            title: '登录成功',
                            duration: 1000,
                            mask: true
                          })
                          setTimeout(function () {
                            wx.navigateBack({});
                          }, 1000);
                        } else {
                          //登录失败
                          wx.showToast({
                            title: '请重新登录',
                            duration: 1500,
                            image: "/static/images/icon_error.png"
                          })
                        }
                      });

                    }
                  })

                }
              });
			      }
          });
        }else{
          //重新请求登录
          wx.login({
            success: function (result) {
              var code = result.code;
              wx.getUserInfo({
                success: function (res) {
                  //存储为全局变量
                  app.globalData.userInfo = res.userInfo;
                  var data = {
                    iv: res.iv,
                    _iv: e.detail.iv,
                    encryptedData: res.encryptedData,
                    _encryptedData: e.detail.encryptedData,
                    code: code,
                    shareId: shareId,
                    spreadId: spreadId,
                    shareType: wx.getStorageSync("shareType")
                  };
                  util.request(api.UserLogin, data).then(function (res) {
                    if (res.code === '200') {
                      var customerId = res.datas.customerId;
                      var openId = res.datas.openId;
                      var token = res.datas.token;
                      var sessionKey = res.datas.sessionKey;
                      wx.setStorageSync("customerId", customerId);
                      wx.setStorageSync("openId", openId);
                      wx.setStorageSync("token", token);
                      wx.setStorageSync("sessionKey", sessionKey);
                      wx.setStorageSync("type", res.datas.type);
                      // wx.setStorageSync("auth", res.datas.auth);
                      if ("0" == res.datas.type || "1" == res.datas.type) {
                        //供应商登录
                        wx.setStorageSync("shareId", res.datas.customerId);
                      } else {
                        //推广人或者消费者登录
                        if (res.datas.shareId) {
                          wx.setStorageSync("shareId", res.datas.shareId)
                        }
                      }
                      wx.showToast({
                        title: '登录成功',
                        duration: 1000,
                        mask: true
                      })
                      setTimeout(function () {
                        wx.navigateBack({});
                      }, 1000);
                    } else {
                      //登录失败
                      wx.showToast({
                        title: '请重新登录',
                        duration: 1500,
                        image: "/static/images/icon_error.png"
                      })
                    }
                  });

                }
              })

            }
          });
        }
       
        return;
      },
      fail:function(){
        //session过期，重新请求登陆
        wx.login({
          success: function (result) {
            var code = result.code;
            wx.getUserInfo({
              success: function (res) {
                //存储为全局变量
                app.globalData.userInfo = res.userInfo;
                var data = {
                  iv: res.iv,
                  _iv: e.detail.iv,
                  encryptedData: res.encryptedData,
                  _encryptedData: e.detail.encryptedData,
                  code: code,
                  shareId: shareId,
                  spreadId: spreadId,
                  shareType:wx.getStorageSync("shareType")
                };
                util.request(api.UserLogin, data).then(function (res) {
                  if (res.code === '200') {
                    var customerId = res.datas.customerId;
                    var openId = res.datas.openId;
                    var token = res.datas.token;
                    var sessionKey = res.datas.sessionKey;
                    wx.setStorageSync("customerId", customerId);
                    wx.setStorageSync("openId", openId);
                    wx.setStorageSync("token", token);
                    wx.setStorageSync("sessionKey",sessionKey);
                    wx.setStorageSync("type", res.datas.type);
                    // wx.setStorageSync("auth", res.datas.auth);
                    if ("0" == res.datas.type || "1" == res.datas.type) {
                      //供应商登录
                      wx.setStorageSync("shareId", res.datas.customerId);
                    }else{
                      //推广人或者消费者登录
                      if(res.datas.shareId){
                        wx.setStorageSync("shareId", res.datas.shareId)
                      }
                    }
                    wx.showToast({
                      title: '登录成功',
                      duration: 1000,
                      mask: true
                    })
                    setTimeout(function () {
                      wx.navigateBack({});
                    }, 1000);
                  } else {
                    wx.showToast({
                      title: '失败，请重试!',
                      duration: 1500,
                      image: "/static/images/icon_error.png"
                    })
                  }
                });

              }
            })

          }
        });
      }
    })
    
  }
})